package top.wuyang.springboot3.schoolTimetable.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import top.wuyang.springboot3.base.PageBean;
import top.wuyang.springboot3.base.R;
import top.wuyang.springboot3.schoolTimetable.dao.TbClassInfoMapper;
import top.wuyang.springboot3.schoolTimetable.entity.TbClassInfo;
import top.wuyang.springboot3.schoolTimetable.service.TbClassInfoService;
import top.wuyang.springboot3.vo.PageVO;

@Service
@Slf4j
@RequiredArgsConstructor
public class TbClassInfoServiceImpl implements TbClassInfoService {
    private final TbClassInfoMapper tbClassInfoMapper;

    @Override
    public R<PageVO<TbClassInfo>> query(TbClassInfo tbClassInfo, PageBean pageBean){
        QueryWrapper<TbClassInfo> wrapper = new QueryWrapper<>();
        wrapper.like(StringUtils.hasText(tbClassInfo.getCname()), "cname", tbClassInfo.getCname());
        IPage<TbClassInfo> page = new Page<>(pageBean.getPageNumber(), pageBean.getPageSize());
        page = tbClassInfoMapper.selectPage(page, wrapper);
        return R.ok(page);
    }


    @Override
    public R<TbClassInfo> queryById(Integer id){
        TbClassInfo tbClassInfo = tbClassInfoMapper.selectById(id);
        return tbClassInfo == null ? R.fail("班级不存在", null) : R.ok("",tbClassInfo);
    }


    private TbClassInfo queryByCname(String cname){
        QueryWrapper<TbClassInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("cname", cname);
        TbClassInfo tbClassInfo = tbClassInfoMapper.selectOne(wrapper);
        return tbClassInfo;
    }


    @Override
    public R<String> insert(TbClassInfo tbClassInfo){
        // 校验
        TbClassInfo check = queryByCname(tbClassInfo.getCname());
        if (check != null) {
            return R.fail("名称已经存在", null);
        }
        int i = tbClassInfoMapper.insert(tbClassInfo);
        return i == 1 ? R.ok("新增成功", null) : R.fail("新增失败", null);
    }

    @Override
    public R<String> update(TbClassInfo tbClassInfo){
        // 校验
        TbClassInfo check = queryByCname(tbClassInfo.getCname());
        if (check != null && !check.getId().equals(tbClassInfo.getId())) {
            return R.fail("名称已经存在", null);
        }
        int i = tbClassInfoMapper.updateById(tbClassInfo);
        return i == 1 ? R.ok("更新成功", null) : R.fail("更新失败", null);
    }

    @Override
    public R<String> delete(Integer id){
        int i = tbClassInfoMapper.deleteById(id);
        return i == 1 ? R.ok("删除成功", null) : R.fail("删除失败", null);
    }



}
